import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_channel_demo/common/Global.dart';
import 'package:flutter_channel_demo/models/worker.dart';
import 'package:flutter_channel_demo/utils/tools.dart';
import 'package:flutter_channel_demo/widgets/popUp.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_channel_demo/api/worker.dart';
import 'package:crypto/crypto.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  bool browseOn = false;

  final TextEditingController _controllerMobile = TextEditingController();
  final TextEditingController _controllerPassword = TextEditingController();

  @override
  initState() {
    _controllerMobile.text = '15678798789';
    _controllerPassword.text = 'Qian2023';
    super.initState();
  }

  String _md5String(String input) {
    // 将输入字符串转换为字节列表
    List<int> bytes = utf8.encode(input);

    // 计算 MD5 值
    Digest md5Digest = md5.convert(bytes);
    // 将计算结果转换为 16 进制字符串
    return md5Digest.toString();
  }

  userLogin() async {
    login(
      _controllerMobile.text.trim(),
      _md5String(_controllerPassword.text.trim()),
      context,
    ).then((result) {
      var data = result['data'];

      if (result['code'] == 20000) {
        Global.worker.token = data['token'];
        Worker worker;
        SharedPreferences.getInstance().then((prefPre) {
          prefPre.setString("token", data['token']);

          getInfo().then((info) {
            if (info['code'] == 20000) {
              worker = Worker.fromJson(info['data']);
              print(worker.toJson());
              // 全局存一份
              SharedPreferences.getInstance().then((pref) {
                pref.setString("token", data['token']);
                pref.setString("worker", jsonEncode(worker.toJson()));
              });
            }

            switchTab(context, '/home');
          });
        });
      } else {
        showAlertPopup(context, '提示', result['message'], '确定');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // var _auth = Provider.of<AuthModel>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title: const Text('登录')),
      body: SafeArea(
        child: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.only(top: 16, bottom: 24),
          width: MediaQuery.of(context).size.width,
          child: Padding(
            padding: const EdgeInsets.all(18.0),
            child: Column(
              children: <Widget>[
                const SizedBox(
                    height: 150.0,
                    child: Padding(
                        padding:
                            EdgeInsets.only(left: 15.0, right: 15.0, top: 30),
                        child: Image(
                          image: AssetImage('assets/images/logo.png'),
                          fit: BoxFit.contain,
                        ))),
                const Padding(padding: EdgeInsets.all(18.0)),
                Form(
                  key: formKey,
                  child: Column(
                    children: [
                      TextFormField(
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: '手机号',
                          hintText: '请输入手机号',
                        ),
                        validator: (v) {
                          return v!.trim().isNotEmpty ? null : '手机号不能为空';
                        },
                        controller: _controllerMobile,
                        keyboardType: TextInputType.phone,
                      ),
                      const Padding(padding: EdgeInsets.all(18.0)),
                      TextFormField(
                        controller: _controllerPassword,
                        readOnly: true,
                        obscureText: !browseOn,
                        validator: (v) {
                          return v!.trim().isNotEmpty ? null : '密码不能为空';
                        },
                        decoration: InputDecoration(
                          border: const OutlineInputBorder(),
                          labelText: '密码',
                          hintText: '请输入密码',
                          suffixIcon: IconButton(
                            icon: browseOn
                                ? const Icon(Icons.visibility_off)
                                : const Icon(Icons.visibility),
                            onPressed: () {
                              setState(() {
                                browseOn = !browseOn;
                              });
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const Padding(padding: EdgeInsets.all(18.0)),
                SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    onPressed: () {
                      if (formKey.currentState!.validate()) {
                        userLogin();
                      }
                    },
                    child: const Text('登录'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
